const WebSocketServer = require("ws").Server;

let wss = new WebSocketServer({
  port: 8181,
  verifyClient: socketVerify,
}); //服务端口8181
let clients = [];

function socketVerify(info) {
  // console.table(info)
  return true;
}

wss.broadcast = function (msg) {
  wss.clients.forEach(function each(client) {
    client.send(msg);
  });
};

const __BEGIN__ = '';
const __HEART__ = 'KEEPALIVE';
const __END__ = '<EOF>';

function handleOpen() {
  console.log('\x1B[43m \x1B[34m', 'ws开启')
};
wss.on("open", handleOpen);

function handleClone() { };
wss.on("clone", handleClone);

function handleError() { };
wss.on("error", handleError);

function handleConnection(ws, req) {
  // console.log('[ req ]', req)
  var name = "服务端";
  var msg = "客户端已连接";
  ws.on("message", (oMsg) => {
    // console.log(oMsg)
    let broadcast = '';//定义广播消息用
    let strMsg = oMsg.toString();//Buffer格式需要转移一次
    let str = strMsg.substring(__BEGIN__.length, strMsg.lastIndexOf(__END__));
    if (str === `${__HEART__}`) {
      console.log('\x1B[43m \x1B[34m', 'isHeart,heart:', '\x1B[0m', `${str}`)
      broadcast = `${__BEGIN__}${__HEART__}${__END__}`;
      // wss.broadcast(broadcast)
      return
    };
    let json = JSON.parse(str);
    console.log(json)
    if (json.msg == 'test') {
      broadcast = `${__BEGIN__}${b}${__END__}`;
    }
    wss.broadcast(broadcast)
  });
  ws.on('error', (err) => {
    console.log(err)
  })
  ws.on('close', (close) => {
    console.log(close)
  })
}
wss.on("connection", handleConnection);


module.exports = wss;